<?php
/**
 *    我的运单列表控制器
 *    @author liangcajian QQ632324010
 */
define('NUM_PER_PAGE', 20); // 每页显示数量 

class My_kdorderApp extends MemberbaseApp
{
  function __construct()
  {
	  $this->My_kdorderApp();
  }
  
  function My_kdorderApp()
  {
	  parent::__construct();
	  $this->_kd_order =& m('kd_order');
	  $this->_kd_yubao_mod =& m('kd_yubao');
  }	
    function index()
    {
        /* 搜索条件 */
        $conditions = "order_alias.user_id = " . $this->visitor->get('user_id');
		//状态
        if (is_numeric($_GET['status']) && $_GET['status']> -1){
            $conditions .= " AND status = '".intval($_GET['status'])."' ";
        }			
        if (isset($_GET['key']) && htmldecode($_GET['key'])){
            $conditions .= " AND (order_sn LIKE '%".htmldecode($_GET['key'])."%' OR txtRece_name LIKE '%".htmldecode($_GET['key'])."%' OR txtRece_mobilephone LIKE '%".htmldecode($_GET['key'])."%' ".
			               "OR yundanhao LIKE '%".htmldecode($_GET['key'])."%' OR Goods_wupin LIKE '%".htmldecode($_GET['key'])."%')";
        }
		//录入时间
		if ($_GET['add_time_from']){
			$conditions.=" AND addtime>=".strtotime($_GET["add_time_from"]." 00:00:00")." ";
		}
		if ($_GET['add_time_to']){
			$conditions.=" AND addtime<=".strtotime($_GET["add_time_to"]." 23:59:59")." ";
		}		
		//更新排序
		if (isset($_GET['sort']) && isset($_GET['order'])){
			$sort  = strtolower(htmldecode($_GET['sort']));
			$order = strtolower(htmldecode($_GET['order']));
			if (!in_array($order,array('asc','desc'))){
			 $sort  = 'addtime';
			 $order = 'desc';
			}
		}else{
			$sort  = 'addtime';
			$order = 'desc';
		}	 
		$pagenum = isset($_GET['pagenum']) ? intval($_GET['pagenum']) : NUM_PER_PAGE;
		$this->assign('pagenum', $pagenum);	  
		$page = $this->_get_page($pagenum); 
		$orders = $this->_kd_order->find(array(
			'join'          => 'has_kdorderextm',
			'fields'        => 'this.*,kd_orderextm.*',
			'conditions'    => $conditions,
			'limit'         => $page['limit'],  //获取当前页的数据
			'order'         => "$sort $order",
			'count'         => true //允许统计
		)); 

		//print_r($orders);
		$page['item_count'] = $this->_kd_order->getCount(); //获取统计的数据
		$this->_format_page($page);  
		$this->assign('page_info', $page); //将分页信息传递给视图，用于形成分页条
		$this->assign('orders', $orders);	 
		$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
									  'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));	   	  
       
	    /* 当前用户中心菜单 */
        $this->_curitem('my_kdorder');
        /* 当前所处子菜单 */
        $this->_curmenu('kdorder_list');
        $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('kdorder_list'));
        $this->display('my_kdorder.index.html');
    }

  /**
   *    添加
   *
   *    @author liangcajian QQ632324010
   *    @return    void
   */
  function add()
  {
	  if (!IS_POST)
	  {
		  $region_mod =& m('kd_fenlei');
		  $regions[0] = $region_mod->get_options(0);
		  $this->assign('regions', $regions);
		  
		  //服务项目
		  $m_kd_fuwu = &af('kd_fuwu');
		  $this->assign('fuwu_data', $m_kd_fuwu->getAll());

		  //快件物品
		  $m_kd_kuaidi = &af('kd_kuaidi');
		  $this->assign('kuaidi_data', $m_kd_kuaidi->getAll());
		  $order_info["goodswupin"] = array( 0 => array( 'yubao_id' => '0', 'PostOfficeID' => '','PostNumber' => '','GoodsName' => '选择物品','GoodsCount' => '0','GoodsWorth' => '0' ));
		  $this->assign('order_info', $order_info);

		  //显示包裹入库记录
//		  $kd_yubao = $this->_kd_yubao_mod->find(array(
//			  'conditions'    => "baoguo = 1 AND status <= 1 AND user_id = " . $this->visitor->get('user_id'),
//			  'limit'         => "10",
//			  'order'         => "yubao_id desc",
//		  )); 
//		  $this->assign('kd_yubao', $kd_yubao);
		
		  /* 四、填写发货地址、填写收货地址 */
		  $model_address =& m('address');
		  $addresses     = $model_address->find(array(
			  'conditions' => 'user_id = ' . $this->visitor->get('user_id'),
			  'order'      => 'case when default_use>0 then 0 else 1 end, default_use DESC, addr_id DESC',
		  ));
		  //设置一个系统自带的发货地址
		  $addresses[1] = array("addr_id" => "1","default_use" => "0","consignee" => $this->visitor->get('user_name'),"address" => "1619 s del mar ave san Gabriel ca91776",
		                        "zipcode" => "90001","phone_mob" => "626-566-7076","ddl_type" => "2","txt_countrys" => "USA//Los Angeles//Gabriel//","txt_company" => "","txt_email" => "","idpic" => "rbtnno");	
								//is_array($addresses) && sort($addresses);//数组排序 		  
		  foreach ($addresses as $key => $list){ $my_address[$list['ddl_type']][] = $list;}
		  $my_address_json = ecm_json_encode($addresses);
		  $this->assign('my_address_json', $my_address_json);
		  $this->assign('my_address', $my_address);
		  //print_r($addresses);
		
		  /* 当前用户中心菜单 */
		  $this->_curitem('my_kdorderadd');
		  /* 当前所处子菜单 */
		  $this->_curmenu('add_kdorder');
		  $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('add_kdorder'));
		  $this->import_resource(array('script' => 'abouts_kuaidi.js'));	
		  $this->display('my_kdorder.form.html');			  
	  }
	  else
	  {
		//检查表单是否已正确填写了
		if ($this->check_form()==true){
		  
			//运单数据提交
			$data = $this->form_post_data();
			if (!$data){
				$this->show_warning("添加运单出错，请重新添加，或者联系管理员处理");
				return;
			}	
			//运单地址提交
			$data_address = $this->form_post_address($data);
            $this->show_message('add_ok',
				'back_list',    'index.php?app=my_kdorder',
				'continue_add', 'index.php?app=my_kdorder&amp;act=add'
             );			
		}
	  }
  }
  function edit()
  {
	  $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
	  if(!$order_id){
		  $this->show_warning('传入的ID为空，请重新操作'); return;
	  }	  
	  if (!IS_POST)
	  {
		  /* 获取订单信息 */
		  $order_info = $this->_kd_order->get(array(
			  'conditions' => " order_alias.order_id = {$order_id} and user_id = " . $this->visitor->get('user_id'),
			  'join'          => 'has_kdorderextm',//取出订单地址
		  ));
		  if(!$order_info){
			  $this->show_warning('没有找该运单信息'); return;
		  }
	   
		  //客户委托项目
		  $region_mod =& m('kd_fenlei');		  
		  $regions = array();//获每一个地区的父ID号出来
		  $date_parentid = $region_mod->find(array( 'conditions' => 'kd_fenlei.region_id' . db_create_in($order_info['xiangmu']) ));
		  foreach ($date_parentid as $key => $parentid){ $regions[] = $region_mod->get_options($parentid['parent_id']); }
		  if(!$regions){ $regions[0] = $region_mod->get_options(0); }
		  $this->assign('regions', $regions);
		  $choose_xiangmu = explode(",",$order_info['xiangmu']);
		  $this->assign('choose_xiangmu', $choose_xiangmu);	
		  
		  //二、快件物品
		  $m_kd_kuaidi = &af('kd_kuaidi');
		  $this->assign('kuaidi_data', $m_kd_kuaidi->getAll());
		  $order_info["goodswupin"] = $this->_kd_yubao_mod->find("order_id=".$order_info['order_id']); 
		  if(!$order_info["goodswupin"]){
		      $order_info["goodswupin"] = array( 0 => array( 'yubao_id' => '0','PostOfficeID' => '','PostNumber' => '','GoodsName' => '选择物品','GoodsCount' => '0','GoodsWorth' => '0' ));
		  }		  
		  
		  //三、选择服务项目
		  $m_kd_fuwu = &af('kd_fuwu');
		  $data_kd_fuwu = $m_kd_fuwu->getAll();
		  foreach ($data_kd_fuwu as $key => $fuwu){ if(strstr($order_info['ServiceItems'],''.$key.'')){ $data_kd_fuwu[$key]['check'] = $key; } }
		  $this->assign('fuwu_data', $data_kd_fuwu);
		  $ServiceItems['Fix'] = explode("//",$order_info['ServiceItemsFix']);
		  $ServiceItems['Bx'] = explode("//",$order_info['ServiceItemsBx']);
		  $this->assign('ServiceItems', $ServiceItems);
		  
		  //四、填写发货地址 五、填写收货地址
		  $countrys1 = explode('//',$order_info['txt_countrys']);
		  $order_info['txt_country'] = $countrys1[0];
		  $order_info['txt_province'] = $countrys1[1];
		  $order_info['txt_city'] = $countrys1[2];
		  $countrys = explode('//',$order_info['txtRece_countrys']);
		  $order_info['txtRece_country'] = $countrys[0];
		  $order_info['txtRece_province'] = $countrys[1];
		  $order_info['txtRece_city'] = $countrys[2];	
		  $order_info['txtqu'] = $countrys[3];		  
		  //json格式已有地址库
		  $model_address =& m('address');
		  $addresses     = $model_address->find(array(
			  'conditions' => 'user_id = ' . $this->visitor->get('user_id'),
			  'order'      => 'case when default_use>0 then 0 else 1 end, default_use DESC, addr_id',
		  )); 
		  //设置一个系统自带的发货地址
		  $addresses[1] = array("addr_id" => "1","default_use" => "0","consignee" => $this->visitor->get('user_name'),"address" => "1619 s del mar ave san Gabriel ca91776",
		                        "zipcode" => "90001","phone_mob" => "626-566-7076","ddl_type" => "2","txt_countrys" => "USA//Los Angeles//Gabriel//","txt_company" => "","txt_email" => "","idpic" => "rbtnno");	
								//is_array($addresses) && sort($addresses);//数组排序  
		  foreach ($addresses as $key => $list){ $my_address[$list['ddl_type']][] = $list;  }
		  $my_address_json = ecm_json_encode($addresses);
		  $this->assign('my_address_json', $my_address_json);
		  $this->assign('my_address', $my_address);
		  
		  //print_r($order_info);
		  $this->assign('order_info', $order_info);		
		  $this->import_resource(array('script' => 'abouts_kuaidi.js'));						
		  /* 当前用户中心菜单 */
		  $this->_curitem('my_kdorder');
		  /* 当前所处子菜单 */
		  $this->_curmenu('edit_kdorder');
		  $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('edit_kdorder'));
		  $this->display('my_kdorder.form.html');
	  }
	  else
	  {
		//检查表单是否已正确填写了
		if ($this->check_form()==true){
			//运单数据提交
			$data = $this->form_post_data($order_id);
			if (!$data){
				$this->show_warning("修改运单出错，请重新添加，或者联系管理员处理");
				return;
			}	
			//运单地址提交
			$data_address = $this->form_post_address($data);
			
            $this->show_message('edit_ok',
				'back_list',    'index.php?app=my_kdorder',
				'重新修改', 'index.php?app=my_kdorder&amp;act=edit&amp;order_id='.$order_id
             );			
		}	 
	  }
  }
  function view()
  {
	  $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
	  /* 获取订单信息 */
	  $order_info = $this->_kd_order->get(array(
		  'conditions' => " order_alias.order_id = {$order_id} and user_id = " . $this->visitor->get('user_id'),
		  'join'          => 'has_kdorderextm',//取出订单地址
	  ));
	  if(!$order_info){
		  $this->show_warning('没有找该运单信息'); return;
	  }
	  
	  //二、快件物品
	  $order_info["goodswupin"] = $this->_kd_yubao_mod->find("order_id=".$order_info['order_id']); 
	  
	  //三、选择服务项目
	  $m_kd_fuwu = &af('kd_fuwu');
	  $data_kd_fuwu = $m_kd_fuwu->getAll();
	  foreach ($data_kd_fuwu as $key => $fuwu){ if(strstr($order_info['ServiceItems'],''.$key.'')){ $data_kd_fuwu[$key]['check'] = $key; } }
	  $this->assign('fuwu_data', $data_kd_fuwu);
	  $ServiceItems['Fix'] = explode("//",$order_info['ServiceItemsFix']);
	  $ServiceItems['Bx'] = explode("//",$order_info['ServiceItemsBx']);
	  $this->assign('ServiceItems', $ServiceItems);
	  $this->assign('order_info', $order_info);		

	  /* 当前用户中心菜单 */
	  $this->_curitem('my_kdorder');
	  /* 当前所处子菜单 */
	  $this->_curmenu('view_kdorder');
	  $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('view_kdorder'));
	  $this->display('my_kdorder.form.html');
  }  
  //表单所有项数据
  function form_post_data($order_id = 0)
  {
	//一、客户委托项目
	$date_xiangmu = $_POST['FromCountry'] ? $_POST['FromCountry'] .','.$_POST['ToCountry'] .','.$_POST['ExpressCompany'] .','.$_POST['TransportType'] : '';
	  
	//二、快件物品详情
	$yubao_data = array();
	if (is_array($_POST['GoodsName']) && count($_POST['GoodsName'])>0){
	  for ($i = 0; $i <count($_POST['GoodsName']);$i++){
		if (!empty($_POST['GoodsName'][$i])){
			$yubao_data[intval($_POST['yubao_id'][$i])] = array(
			   'yubao_id' => intval($_POST['yubao_id'][$i]),
			   'PostOfficeID' => htmldecode($_POST['PostOfficeID'][$i]),
			   'yundanhao' => htmldecode($_POST['PostNumber'][$i]),
			   'user_id' => $this->visitor->get('user_id'),
			   'user_name' => $this->visitor->get('user_name'),
			   'GoodsName' => htmldecode($_POST['GoodsName'][$i]),
			   'GoodsCount' => intval($_POST['GoodsCount'][$i]),
			   'GoodsWorth' => intval($_POST['GoodsWorth'][$i]),
			   'updatetime' => time(),		
			);
			$goods_wupin[] = array('PostOfficeID' => htmldecode($_POST['PostOfficeID'][$i]),'PostNumber' => htmldecode($_POST['PostNumber'][$i]) );			
		}		  
	  }			
	}
	if($goods_wupin){ $data_goods_wupin = serialize($goods_wupin); }
	
	//三、选择服务项目
	$data_ServiceItems = $_POST['ServiceItems'] ? implode(",",$_POST['ServiceItems']) : '';
	if ($_POST['ServiceItemsFix']){ 
	   $data_ServiceItemsFix = intval($_POST['ServiceItemsFix']) .'//'. intval($_POST['SinglgFixAmount']) .'//'. $_POST['SingleFixMemo'];
	}
	if ($_POST['ServiceItemsBx']){ 
	   $data_ServiceItemsBx = intval($_POST['ServiceItemsBx']) .'//'. abs(floatval($_POST['ProtectAmount']));
	}	
	
	$data = array(
	  'xiangmu'        =>  $date_xiangmu,
	  'FaHuoDi'        =>  $_POST['FaHuoDi'],
	  'ShouHuoDi'      =>  $_POST['ShouHuoDi'],
	  'CangKuDiZhi'    =>  $_POST['CangKuDiZhi'],
	  'ZhuanYunFangShi'=>  $_POST['ZhuanYunFangShi'],
	  'Goods_wupin'    =>  $data_goods_wupin,
	  'SumGoodsAmount' =>  intval($_POST['SumGoodsAmount']),
	  'SumGoodsWorth'  =>  abs(floatval($_POST['SumGoodsWorth'])),
	  'ServiceItems'   =>  $data_ServiceItems,
	  'ServiceItemsFix'=> $data_ServiceItemsFix,
	  'ServiceItemsBx' =>  $data_ServiceItemsBx,
	  'Memo'           =>  trim($_POST['Memo']),
	  'updatetime'     =>  time(),
	);
	
	 /* 保存运单到数据表 */
	if ($order_id>0){	
        $this->_kd_order->edit($order_id, $data);
		if ($this->_kd_order->get_error()){
			$this->show_warning($this->_kd_order->get_error());
			return;
		}
		$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '修改快递运单,ID:'.$order_id, 0);//添加操作日志
		
		/* 如果快件物品详情不同了，把快件物品详情删除掉 */
		$yubao_diff = $this->_kd_yubao_mod->find(array( 'conditions' => "order_id = '{$order_id}'", 'fields' => 'yubao_id' ));
		$drop_yubao_ids = array_diff(array_keys($yubao_diff), array_keys($yubao_data));		
		if (!empty($drop_yubao_ids))
		{
			$this->_kd_yubao_mod->drop($drop_yubao_ids);
		}
						
	}
	else
	{
		$data['order_sn'] = $this->_gen_order_sn();
		$data['addtime'] = time();
		$data['user_id'] = $this->visitor->get('user_id');
		$data['user_name'] = $this->visitor->get('user_name');		
		$order_id = $this->_kd_order->add($data);
		if (!$order_id){
			$this->show_warning($this->_kd_order->get_error());
			return;
		}
		$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '添加快递运单,ID:'.$order_id, 0);//添加操作日志		
	}
	
	//二、添加/修改快件物品详情
	foreach ($yubao_data as $key => $yubao){
		$yubao['order_id'] = $order_id;
		if ($yubao['yubao_id']){
			$this->_kd_yubao_mod->edit($yubao['yubao_id'], $yubao);
		}else{
			$yubao['addtime'] = time();
			$this->_kd_yubao_mod->add($yubao);
		}
	}		
		  
	return $order_id;
  }

  //添加运单地址到运单地址表里
  function form_post_address($order_id = 0)
  {	 
	  //四、填写发货地址
	  $data = array(
		'order_id' =>  $order_id,//关联运单订单
		'txt_id' =>  htmldecode($_POST['address_options']),//id
		'txt_name' =>  htmldecode($_POST['txt_name']),//姓名
		'txt_company' =>  htmldecode($_POST['txt_company']),//公司
		'txt_mobilephone' =>  htmldecode($_POST['txt_mobilephone']),//手机电话
		'txt_email' =>  htmldecode($_POST['txt_email']),//邮箱地址
		'txt_countrys' =>  htmldecode($_POST['txt_country']).'//'.htmldecode($_POST['txt_province']).'//'.htmldecode($_POST['txt_city']),//国家/地区/省/市
		'txt_address' =>  htmldecode($_POST['txt_address']),//详细地址
		'txt_postoffice' =>  htmldecode($_POST['txt_postoffice']),//邮政
		'txtRece_id' =>  htmldecode($_POST['address_options1']),//id
		'txtRece_name' =>  htmldecode($_POST['txtRece_name']),//姓名
		'txtRece_company' =>  htmldecode($_POST['txtRece_company']),//公司
		'txtRece_mobilephone' =>  htmldecode($_POST['txtRece_mobilephone']),//手机电话
		'txtRece_email' =>  htmldecode($_POST['txtRece_email']),//邮箱地址
		'txtRece_countrys' =>  htmldecode($_POST['txtRece_country']).'//'.htmldecode($_POST['txtRece_province']).'//'.htmldecode($_POST['txtRece_city']).'//'.htmldecode($_POST['txtqu']),//国家/地区/省/市
		'txtRece_address' =>  htmldecode($_POST['txtRece_address']),//详细地址
		'idpic' =>  htmldecode($_POST['idpic']),//大陆非大陆
		'txtidcode' =>  htmldecode($_POST['txtidcode']),//身份证
		'txtRece_postoffice' =>  htmldecode($_POST['txtRece_postoffice']),//邮政
	  );
	    
	  /*  检查是否添加发货地址 ========================================================== */
	  $model_address =& m('address');
	  if (intval($_POST['address_options']) <= 0 && intval($_POST['save_address']) == 1)
	  {
		   $data_address = array(
			  'user_id'       => $this->visitor->get('user_id'),
			  'consignee'     => $data['txt_name'],//姓名
			  'txt_company'   => $data['txt_company'],//公司
			  'phone_mob'     => $data['txt_mobilephone'],//手机电话
			  'txt_email'     => $data['txt_email'],//邮箱地址
			  'txt_countrys'  => $data['txt_countrys'],//详细地址
			  'address'       => $data['txt_address'],//详细地址			  
			  'zipcode'       => $data['txt_postoffice'],//邮政
			  'ddl_type'     => 2,
			  'addtime'   => time(),
		  );
		  $txt_id = $model_address->add($data_address);
		  $txt_id && $data['txt_id'] = $txt_id;
	  }
	  /*  检查是否添加收货地址 ========================================================== */
	  if (intval($_POST['address_options1']) <= 0 && intval($_POST['save_address1']) == 1)
	  {
		   $data_address1 = array(
			  'user_id'       => $this->visitor->get('user_id'),
			  'consignee'     => $data['txtRece_name'],//姓名
			  'txt_company'   => $data['txtRece_company'],//公司
			  'phone_mob'     => $data['txtRece_mobilephone'],//手机电话
			  'txt_email'     => $data['txtRece_email'],//邮箱地址
			  'txt_countrys'  => $data['txtRece_countrys'],//详细地址
			  'address'       => $data['txtRece_address'],//详细地址
			  'idpic'         => $data['idpic'],//大陆非大陆
			  'txtidcode'     => $data['txtidcode'],//身份证			  
			  'zipcode'       => $data['txtRece_postoffice'],//邮政
			  'ddl_type'      => 1,
			  'addtime'   => time(),
		  );
		  $txtRece_id = $model_address->add($data_address1);
		  $txtRece_id && $data['txtRece_id'] = $txtRece_id;
	  }	
	  /*  检查是否添加收货人地址 ========================================================== */		 
	     
	  $mod_kd_order_extm =& m('kd_orderextm'); 
	  /* 保存运单地址到运单地址库里 */
	  if (intval($_POST['extm_id'])>0){	
		  $mod_kd_order_extm->edit(intval($_POST['extm_id']), $data);
	  }else{
		  $data1['add_time'] = time();
		  $mod_kd_order_extm->add($data);
	  }
	  if ($mod_kd_order_extm->get_error()){
		  $this->show_warning($mod_kd_order_extm->get_error());
		  return;
	  }
 		  
  }
  
  //检查表单的必填项
  function check_form()
  {  
	  if (!$_POST['FromCountry'] && !$_POST['FaHuoDi']){ $this->show_warning('请选择发货地'); return false; }
	  if (!$_POST['ToCountry'] && !$_POST['ShouHuoDi']){ $this->show_warning('请选择收货地'); return false; }
	  if (!$_POST['ExpressCompany'] && !$_POST['CangKuDiZhi']){ $this->show_warning('请选择所在仓库'); return false; }
	  if (!$_POST['TransportType'] && !$_POST['ZhuanYunFangShi']){ $this->show_warning('请选择转运方式'); return false; }
	  if (is_array($_POST['GoodsName']) && count($_POST['GoodsName'])>0){
	    for ($i = 0; $i <count($_POST['GoodsName']);$i++){
		  if (empty($_POST['GoodsName'][$i]) or $_POST['GoodsName'][$i]=="选择物品" ){ $this->show_warning('物品名不能为空'); return false; }
		  if (empty($_POST['GoodsCount'][$i]) or $_POST['GoodsCount'][$i]<=0 ){ $this->show_warning('物品数量不能为空且必须大于0'); return false; }
		  if (empty($_POST['GoodsCount'][$i]) or $_POST['GoodsCount'][$i]<=0 ){ $this->show_warning('物品价值不能为空且必须大于0'); return false; }
	    }			
	  }
	  if ($_POST['ServiceItemsFix']){ 
	     if (empty($_POST['SinglgFixAmount'])){ $this->show_warning('内部单件物品加固数量不能为空'); return false; }
		 if (empty($_POST['SingleFixMemo'])){ $this->show_warning('内部单件物品加固备注不能为空'); return false; }
	  }
	  if ($_POST['ServiceItemsBx']){ 
	     if (empty($_POST['ProtectAmount'])){ $this->show_warning('保价金额不能为空'); return false; }
	  }	  
	  if (empty($_POST['txt_name'])){ $this->show_warning('寄件人姓名不能为空'); return false; }
	  if (empty($_POST['txt_mobilephone'])){ $this->show_warning('寄件人手机/电话不能为空'); return false; }
	  if (empty($_POST['txt_country'])){ $this->show_warning('寄件人所在国家不能为空'); return false; }
	  if (empty($_POST['txt_city'])){ $this->show_warning('寄件人所在城市不能为空'); return false; }
	  if (empty($_POST['txt_address'])){ $this->show_warning('寄件人详细地址不能为空'); return false; }
	  if (empty($_POST['txtRece_name'])){ $this->show_warning('收件人姓名不能为空'); return false; }
	  if (empty($_POST['txtRece_mobilephone'])){ $this->show_warning('收件人手机/电话不能为空'); return false; }
	  if (empty($_POST['txtRece_country'])){ $this->show_warning('收件人所在国家不能为空'); return false; }
	  if (empty($_POST['txtRece_city'])){ $this->show_warning('收件人所在城市不能为空'); return false; }
	  if (empty($_POST['txtRece_address'])){ $this->show_warning('收件人详细地址不能为空'); return false; }
  
	  return true;
  }
  /** 生成订单号 @author liangcajian QQ632324010 */
  function _gen_order_sn()
  {
	  /* 选择一个随机的方案 */
	  mt_srand((double) microtime() * 1000000);
	  $timestamp = gmtime();
	  $y = date('y', $timestamp);
	  $z = date('z', $timestamp);
	  $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	  $model_order =& m('kd_order');
	  $orders = $model_order->find('order_sn=' . $order_sn);
	  if (empty($orders)){
		  return $order_sn;/* 否则就使用这个订单号 */
	  }
	  return $this->_gen_order_sn();/* 如果有重复的，则重新生成 */
  }
  
  //删除数据
  function drop()
  {
	  $id = isset($_GET['id']) ? htmldecode($_GET['id']) : '';
	  if (!$id)
	  {
		  $this->show_warning('请选择需要删除的记录');
		  return;
	  }
	  $this->_kd_order->drop("user_id = " .$this->visitor->get('user_id') . ' AND status = 0 AND ' . db_create_in($id,'order_id'));
	  $mod_kd_order_extm =& m('kd_orderextm'); 
	  $mod_kd_order_extm->drop(db_create_in($id,'order_id'));
	  $mod_yubao_extm =& m('kd_yubao'); 
	  $mod_yubao_extm->drop(db_create_in($id,'order_id'));	  
	  if ($this->_kd_order->has_error())
	  {
		  $this->show_warning($this->_kd_order->get_error());
		  return;
	  }
	  $this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '删除运单,ID:'.$id, 0);//添加操作日志

	  $this->show_message('drop_ok');	
  }
  
  //导入运单，用excel导入
  function import()
  {
	  if (!IS_POST)
	  {
		  /* 当前用户中心菜单 */
		  $this->_curitem('my_kdorder');
		  /* 当前所处子菜单 */
		  $this->_curmenu('import_kdorder');
		  $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('import_kdorder'));
		  $this->display('my_kdorder.form.html');			  
	  }
	  else
	  {
		  $leadExcel=$_FILES['file']; 
		  if(!$leadExcel['name'] ){ $this->show_warning("请选择需要导入的运单模板Excel文件"); return; } 
		  if($leadExcel['name'] == basename($leadExcel['name'],'.xls')){ $this->show_warning('上传失败，指定的文件不是正确的（.xls）文件格式的类型！'); return; }	
		  if($_FILES['file']['size'] > 1048576){ $this->show_warning('上传失败，上传的文件大小不能超过1MB！'); return; }	

		  $filePath = 'data/files/mall/application/'; //自己设置的上传文件存放路径   
		  $filename = $leadExcel['name'];   //获取上传的文件名   
		  $filetempname = $leadExcel['tmp_name'];   //上传到服务器上的临时文件名   
		  $filename = explode(".",$filename);//把上传的文件名以"."好为准做一个数组。    
		  $filename[0] = 'kdorder_' . date("ymdHis") .'_' .rand(1,100);//取文件名t替换 
		  $name=implode (".",$filename); //上传后的文件名    
		  $uploadfile = $filePath.$name;//上传后的文件名地址				   
		  
		  $result=move_uploaded_file($filetempname,$uploadfile);//假如上传到当前目录下     
		  if($result) //如果上传文件成功，就执行导入excel操作   
		  { 			  
			  import('excel_reader.lib');//导入上传类
			  $data = new Spreadsheet_Excel_Reader();
			  $data->setOutputEncoding('UTF-8');
			  $data->read($uploadfile);
			  error_reporting(E_ALL ^ E_NOTICE);
			  unlink ($uploadfile); //删除上传的excel文件
			  
			  if(!$data->sheets[0]['cells']){ $this->show_warning('上传文件失败，获取不到Excel的数据，检查内容格式是否有误，或者文件超过了最大限制！'); return;  }
			  
			  //标题行
			  $row_title = array( 1 => "发货地", 2 => "收货地", 3 => "仓库地址", 4 => "转运方式", 5 => "所属公司", 6 => "包裹跟踪号", 7 => "物品名称", 8 => "物品数量", 9 => "物品价值($)", 10 => "物品重量(磅)",
								 11 => "保险金额", 12 => "发件人名称", 13 => "发件人手机", 14 => "发件国家", 15 => "发件人省", 16 => "发件人市", 17 => "发件人邮编", 18 => "发件人地址", 19 => "收件人名称", 20 => "收件人身份证号码",
								 21 => "收件人手机", 22 => "收货人所在省", 23 => "收货人所在市", 24 => "收件人所在区", 25 => "收件人邮编", 26 => "收货人详细地址", 27 => "备注", 28 => "入仓号", 29 => "包裹货号", 30 => "报关单号",
								 31 => "快递公司", 32 => "快递单号", 33 => "运单号" );
			  $to_compare = array_diff($row_title, $data->sheets[0]['cells'][1]);//第一行进行比较
			  if($to_compare){ $this->show_warning('上传文件失败，导入的文件格式有误，请下载最新文件格式！'); return; }
			  if(count($data->sheets[0]['cells'])>501){ $this->show_warning('上传文件失败，由于有多重复杂的判断对比，所以一次最多导入500条记录！'); return; }

			  //过滤相同的内容==================================================================================
			  $array_unique_2d = $this->array_unique_2d($data->sheets[0]['cells'],array(7,8,9,21,22,23,24,26));//判断物品数量、价值、收货人名称、收货人电话、收货地址一致时不给插入
			  $data_cells_list = $array_unique_2d['data'];
			  if ($array_unique_2d['unsetData']){
				  $unsetData = implode(',',$array_unique_2d['unsetData']);
				  $unsetData = "，注意：此次导入第".$unsetData."行数据重复性很大，已被过滤";
			  }
			  
			  //判断是否是有效内容==============================================================================
			  $err_text = "";
			  foreach ($data_cells_list as $i => $data_cells )
			  {
				 if($i>1)//$i>1时//第一行的不处理
				 {
					if(!$data_cells[1]){ $err_text .= $row_title[1]."不能为空、";  }
					if(!$data_cells[2]){ $err_text .= $row_title[2]."不能为空、";  }
					if(!$data_cells[3]){ $err_text .= $row_title[3]."不能为空、";  }
					if(!$data_cells[4]){ $err_text .= $row_title[4]."不能为空、";  }
					if(!$data_cells[5]){ $err_text .= $row_title[5]."不能为空、";  }
					if(!$data_cells[6]){ $err_text .= $row_title[6]."不能为空、";  }
					if(!$data_cells[7]){ $err_text .= $row_title[7]."不能为空、";  }
					if(!$data_cells[8]){ $err_text .= $row_title[8]."不能为空、";  
					}else{
						if (!is_numeric($data_cells[8])){ $err_text .= $row_title[8]."必须是数字、"; }
					}
					if(!$data_cells[9]){ $err_text .= $row_title[9]."不能为空、";  
					}else{
						if (!is_numeric($data_cells[9])){ $err_text .= $row_title[9]."必须是数字、"; }
					}
					if($data_cells[10]){
						if (!is_numeric($data_cells[10])){ $err_text .= $row_title[10]."必须是数字、"; }
					}				  
					if($data_cells[11]){
						if (!is_numeric($data_cells[11])){ $err_text .= $row_title[11]."必须是数字、"; }
					}
					//发货人手机
					if($data_cells[13]){
						$isFormat = "/^[0-9\\-]*$/";
						$newstr_phone = str_replace("-","",$data_cells[13]);
						if (!preg_match($isFormat, $data_cells[13])){ $err_text .= $row_title[13]."必须是数字和横线、"; }
						if (strlen($newstr_phone) < 10 || strlen($newstr_phone) > 13 ){ $err_text .= $row_title[13]."必须是大于等于10位或者小于等于13位的有效号码、"; }
					}	
					//收件人信息
					if(!$data_cells[19]){ $err_text .= $row_title[19]."不能为空、"; }	
					if($data_cells[20]){
						if (strlen($data_cells[20]) != 15 && strlen($data_cells[20]) != 18 ){ $err_text .= $row_title[20]."必须是15位或者18位的有效号码、"; }
					}
					if(!$data_cells[21]){ $err_text .= $row_title[21]."不能为空、";  
					}else{
						$isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
						$isMob = "/^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/";
						if(!preg_match($isMob,$data_cells[21]) && !preg_match($isTel,$data_cells[21])){
							  $err_text .= $row_title[21]."格式不正确，如果是固话，必须格式如(xxx-xxxxxxx)、";
						}
					}	
					if(!$data_cells[22]){ $err_text .= $row_title[22]."不能为空、"; } 
					if(!$data_cells[23]){ $err_text .= $row_title[23]."不能为空、"; }
					if(!$data_cells[24]){ $err_text .= $row_title[24]."不能为空、"; }
					if(!$data_cells[25]){ $err_text .= $row_title[25]."不能为空、"; }
					if(!$data_cells[26]){ $err_text .= $row_title[26]."不能为空、"; }
									
					//有错误内容，则提示出来
					if($err_text){
					   $this->show_warning("第".$i."行：" . $err_text); return;
					}
					//查询数据库中是否存在记录了
					$conditions = "(ex.txtRece_name='".$data_cells[19]."' AND ex.txtRece_mobilephone='".$data_cells[21]."') OR o.expressNo='".$data_cells[33]."' OR o.yundanhao='".$data_cells[32]."'";
					$sql="SELECT o.yundanhao,o.expressNo,o.SumGoodsAmount,o.SumGoodsWorth,ex.txtRece_name,ex.txtRece_address FROM ".DB_PREFIX."kd_order AS o ".
						 "LEFT JOIN ".DB_PREFIX."kd_order_extm AS ex ON o.order_id = ex.order_id WHERE {$conditions}";
					$search_data = $this->_kd_order->getRow($sql);
					if($search_data){
						//判断物品数量、价值、收货地址一致时不给插入
						if($search_data['SumGoodsAmount']==$data_cells[8] && $search_data['SumGoodsWorth']==$data_cells[9] && $search_data['txtRece_address']==$data_cells[26]){
							$this->show_warning("第".$i."行记录已经存在，请修改后重新导入"); return;
						}
						if($search_data['yundanhao']==$data_cells[32]){
							$this->show_warning("第".$i."行记录的发货快递单号已存在，请修改后重新导入"); return;
						}
						if($search_data['yundanhao']==$data_cells[33]){
							$this->show_warning("第".$i."行记录的运单号已存在，请修改后重新导入"); return;
						}													  
					}
				 }
			  }	
			  //判断是否是有效内容===============================================================================
			  
			  $mod_kd_order_extm =& m('kd_orderextm');
			  $success_text="";$order_ids = array();
			  //for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++)//$i=2时//第一行的不处理
			  foreach ($data_cells_list as $i => $data_cells )
			  {
				 if($i>1)//$i>1时//第一行的不处理
				 {
					 $goods_wupin[0] = array('PostOfficeID' => $data_cells[5],'PostNumber' => $data_cells[6], );	
					 if($goods_wupin){ $data_goods_wupin = serialize($goods_wupin); }						   
					 $order_id = $this->_kd_order->add(array(
					   'order_sn' => $this->_gen_order_sn(),
					   'user_id' => $this->visitor->get('user_id'),
					   'user_name' => $this->visitor->get('user_name'),						 
					   'FaHuoDi' => htmldecode($data_cells[1]),
					   'ShouHuoDi' => htmldecode($data_cells[2]),
					   'CangKuDiZhi' => htmldecode($data_cells[3]),
					   'ZhuanYunFangShi' => htmldecode($data_cells[4]),
					   'Goods_wupin' => htmldecode($data_goods_wupin),
					   'SumGoodsAmount' => htmldecode($data_cells[8]),
					   'SumGoodsWorth' => htmldecode($data_cells[9]),
					   'ServiceItemsBx' => $data_cells[11] ? "11//".htmldecode($data_cells[11]) : '',
					   'Memo' => htmldecode($data_cells[27]),
					   'zhudanNo' => htmldecode($data_cells[28]),
					   'baoguoNo' => htmldecode($data_cells[29]),
					   'baoguanNo' => htmldecode($data_cells[30]),
					   'express' => htmldecode($data_cells[31]),
					   'expressNo' => htmldecode($data_cells[32]),
					   'yundanhao' => htmldecode($data_cells[33]),
					   'admin_genzong' => '会员:'.$this->visitor->get('user_name').'通过批量导入功能导入的运单',	
					   'addtime' => time(),	
					   'updatetime' => time(),		
					 ));
					 if (!$order_id){ $this->show_warning($this->_kd_order->get_error()); return; }	
					 $order_ids[] = $order_id;  
					  $this->_kd_yubao_mod->add(array(
						 'order_id' =>  $order_id,//关联运单订单
						 'user_id' => $this->visitor->get('user_id'),
						 'user_name' => $this->visitor->get('user_name'),
						 'PostOfficeID' => htmldecode($data_cells[5]),
						 'yundanhao' => htmldecode($data_cells[6]),
						 'GoodsName' => htmldecode($data_cells[7]),
						 'GoodsCount' => htmldecode($data_cells[8]),
						 'GoodsWorth' => htmldecode($data_cells[9]),
						 'GoodsWeight' => htmldecode($data_cells[10]),
						 'addtime' => time(),	
						 'updatetime' => time(),		
					  ));
					  if ($this->_kd_yubao_mod->get_error()){ $this->show_warning($this->_kd_yubao_mod->get_error()); return; }	
					  $mod_kd_order_extm->add(array(
						'order_id' =>  $order_id,//关联运单订单
						'txt_name' =>  htmldecode($data_cells[12]),//姓名
						'txt_mobilephone' =>  htmldecode($data_cells[13]),//手机电话
						'txt_countrys' =>  htmldecode($data_cells[14].'//'.$data_cells[15].'//'.$data_cells[16]),//国家/地区/省/市
						'txt_address' =>  htmldecode($data_cells[18]),//详细地址
						'txt_postoffice' =>  htmldecode($data_cells[17]),//邮政
						'txtRece_name' =>  htmldecode($data_cells[19]),//姓名
						'txtRece_mobilephone' =>  htmldecode($data_cells[21]),//手机电话
						'txtRece_countrys' =>  htmldecode('中国//'.$data_cells[22].'//'.$data_cells[23].'//'.$data_cells[24]),//国家/地区/省/市
						'txtRece_address' =>  htmldecode($data_cells[26]),//详细地址
						'idpic' =>  'rbtnyes',//大陆非大陆
						'txtidcode' =>  htmldecode($data_cells[20]),//身份证
						'txtRece_postoffice' =>  htmldecode($data_cells[25]),//邮政
						'add_time' =>  time(),//时间
					  ));
					  if ($this->_kd_yubao_mod->get_error()){ $this->show_warning($this->mod_kd_order_extm->get_error()); return; }	
				  }
			  }	

			  $this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '通过Excel批量导入成功,ID:'.implode(',',$order_ids), 0);//添加操作日志
			  $this->show_message('批量导入成功'.$unsetData,'back_list', 'index.php?app=my_kdorder' );
			  		   
		  }else{
			  $this->show_warning('上传文件失败，检测到空间上传功能关闭，请联系管理员处理！'); return;
		  }
	  }	  
  }
  //批量导入过滤相同的数组内容
  function array_unique_2d($array, $no_in)
  {
	  //已删除的列值
	  $unset_data = array(); 
	  foreach($array as $key => $val){
		  $i = 0;
		  foreach($array as $k => $v){
			  $diff = json_encode($val) == json_encode($v);
			  if( $diff && $i == 0 ){
				  $i++;
				  continue;
			  }else if($diff){
				  $unset_data[] = $k;
				  unset($array[$k]);
			  }
			  
		  }
	  }

	  //第二次过滤,过滤指定的字段
	  if($no_in)
	  {
		  foreach($array as $key => $val){
			  $ii = 0;
			  foreach($array as $k => $v){
				  $diif1 = array($val[$no_in[0]],$val[$no_in[1]],$val[$no_in[2]],$val[$no_in[3]],$val[$no_in[4]],$val[$no_in[5]],$val[$no_in[6]],$val[$no_in[7]]);
				  $diif2 = array($v[$no_in[0]],$v[$no_in[1]],$v[$no_in[2]],$v[$no_in[3]],$v[$no_in[4]],$v[$no_in[5]],$v[$no_in[6]],$v[$no_in[7]]);
				  $diff = json_encode($diif1) == json_encode($diif2);
				  if( $diff && $ii == 0 ){
					  $ii++;
					  continue;
				  }else if($diff){
					  $unset_data[] = $k;
					  unset($array[$k]);
				  }
			  }		  
		  }
	  }

	  return array( 'data' => $array, 'unsetData' => $unset_data);
  }
  
  //立即付款
  function payment()
  {
	  $order_id = isset($_GET['order_id']) ? $_GET['order_id'] : 0;
	  /* 获取订单信息 */
	  $order_info = $this->_kd_order->get(array(
		  'conditions' => " order_alias.order_id = {$order_id} AND order_alias.status = '3'  AND user_id = " . $this->visitor->get('user_id'),
	  ));
	  if(!$order_info){ $this->show_warning('该运单信息不存在 或者 不是待付款状态'); return; }
	  $order_total_amount = $order_info['totalfei'];
	  $my_money_mod =& m('my_money');
	  
	  if (!IS_POST)
	  {		
		$this->assign('order', $order_info);
		
		//print_r($order_info);
		
		//我的可用余额-------------------------------
		$my_money=$my_money_mod->getRow("select money,zf_pass from {$my_money_mod->table} where user_id='{$this->visitor->get('user_id')}'");	
		//判断我的可用余额是否足免来支付订单
		if( $my_money['money'] )//余额大于0者
		{
			if( $my_money['money'] >= $order_total_amount)
			{
				$my_money['balance_payment'] = 'ok';//您有足够的余额来支付订单，所以显示可用余额支付
			}else{
				$my_money['differ_amount'] = round($order_total_amount-$my_money['money'],2);//还差多少钱，使用网银充值
			}
		}
		$this->assign('my_money', $my_money);			
		$this->_config_seo('title', '请支付您的运单 - ' . Conf::get('site_title'));
		$this->display('my_kdorder.payment.html');
	  
	  }else{
			$password = isset($_POST['password']) ? $_POST['password'] : '';
			$order_id = isset($_POST['order_id']) ? $_POST['order_id'] : 0;
			if (empty($password)){ $this->show_warning('请输入支付密码'); return; }
			//读原始密码
			$my_money=$my_money_mod->getRow("select zf_pass,money from {$my_money_mod->table} where user_id='{$this->visitor->get('user_id')}'");
			if (empty($my_money['zf_pass'])){
				$this->show_warning('您还没设置支付密码，无法支付','设置支付密码','index.php?app=my_money&act=setpaypassword'); 
				return;	
			}	
			//转换32位 MD5
			$md5zf_password=md5($password);	
			if($md5zf_password != $my_money['zf_pass']){ $this->show_warning('支付密码错误，请重新输入'); return; }	
			//如果总金额为0元，则无法支付
			if ( $order_total_amount <= 0){ $this->show_warning('订单总金额小于等于0，无法支付'); return; }			
			if ($my_money['money'] < $order_total_amount){ $this->show_warning('您的帐户余额不足，无法支付订单'); return; }	
			
			//所有判断通过，可以更新订单和减少帐户余额了						
			$order_edit_array=array('money'=>$my_money['money']-$order_total_amount);
			$my_money_mod->edit('user_id='.$this->visitor->get('user_id'), $order_edit_array);
			//添加扣除金额的日志
			$log_text =$this->visitor->get('user_name').'余额支付运单'.$order['order_sn'].':'.$order_total_amount.Lang::get('yuan');
			$my_moneylog_mod =& m('my_moneylog');
			$my_moneylog_mod->add(array(
				'user_id'=>$this->visitor->get('user_id'),
				'user_name'=>$this->visitor->get('user_name'),
				'bank_name'=>'yue',//余额支付
				'add_time'=>gmtime(),
				'leixing'=>20, //订单支出	
				'caozuo'=>1, //状态已完成	
				'money'=>$order_total_amount,
				'money_yue'=>$order_edit_array['money'],//余额
				'log_text'=>$log_text,		
				's_and_z'=>2,//收入1,支出2	
			));	
			//通过检验，更新订单为已付款
			$ebank_type_check = Lang::get('ebank_type');//银行信息
			$this->_kd_order->edit($order_info['order_id'],array(
				'status'=> 5,//已付款，待发货的状态
				'pay_time' =>gmtime(),
			));	
			
			$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '支付快递运单,ID:'.$order_info['order_id'], 0);//添加操作日志
					
            $this->show_message('恭喜您支付成功', 'back_list', 'index.php?app=my_kdorder' );	
	  }
	  
  }
	
    /**
     *    三级菜单
     *
     *    @author liangcajian QQ632324010
     *    @return    void
     */
    function _get_member_submenu()
    {
        $menus = array(
            array(
                'name'  => 'kdorder_list',
                'url'   => 'index.php?app=my_kdorder',
            ),
            array(
                'name'  => 'add_kdorder',
                'url'   => 'index.php?app=my_kdorder&act=add',
            ),
            array(
                'name'  => 'import_kdorder',
                'url'   => 'index.php?app=my_kdorder&act=import',
            ),			
        );
        if (ACT == 'edit')
        {
            $menus[] = array(
                'name' => 'edit_kdorder',
                'url'  => '',
            );
        }elseif (ACT == 'view')
        {
            $menus[] = array(
                'name' => 'view_kdorder',
                'url'  => '',
            );
        }
        return $menus;
    }
}

?>